%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     时间管理器
%%% @end
%%%-------------------------------------------------------------------
-module(time_mgr).

-behaviour(gen_server).

-export([start_link/0]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-include("env.hrl").

-define(timer_ticket, erlang:send_after(timer:seconds(1), erlang:self(), timeout)).


%%%===================================================================
%%% Spawning and gen_server implementation
%%%===================================================================

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).


-ifdef(debug).
init([]) ->
    {ok, undefined, 0}.
-else.
init([]) ->
    {ok, undefined}.
-endif.

handle_call(_Request, _From, State) ->
    {reply, ok, State}.

handle_cast(_Request, State) ->
    {noreply, State}.

handle_info(timeout, State) ->
    ?timer_ticket,
    ticket(),
    {noreply, State};
handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


%%%===================================================================
%%% Internal functions
%%%===================================================================

ticket() ->
    {MegaSecs, Secs, MicroSecs} = os:timestamp(),
    case env_mgr:get(?ENV_TIME_NOW) of
        {_MegaSecs, _Secs, _MicroSecs, Shift} -> env_mgr:set(?ENV_TIME_NOW, {MegaSecs, Secs, MicroSecs, Shift});
        _ -> env_mgr:set(?ENV_TIME_NOW, {MegaSecs, Secs, MicroSecs, 0})
    end.
